package cn.java.caixiaoqing.web.servlet;

import cn.java.caixiaoqing.domain.Person;
import cn.java.caixiaoqing.domain.Student;
import cn.java.caixiaoqing.domain.Teacher;
import cn.java.caixiaoqing.service.PersonService;
import cn.java.caixiaoqing.service.StudentService;
import cn.java.caixiaoqing.service.TeacherService;
import cn.java.caixiaoqing.service.impl.PersonServiceImpl;
import cn.java.caixiaoqing.service.impl.StudentServiceImpl;
import cn.java.caixiaoqing.service.impl.TeacherServiceImpl;
import net.sf.json.JSONArray;

import java.io.IOException;
import java.util.List;

public class ListServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        String tableName = request.getParameter("tableName");
//        System.out.println(tableName);

        JSONArray jsonArray = null;

        if (tableName == null) return;

        if (tableName.equals("student")){
            StudentService studentService = new StudentServiceImpl();
            List<Student> students = studentService.finAllStudents();
//            for (Student student : students) {
//                System.out.println(student);
//            }
            jsonArray = JSONArray.fromObject(students);
        }
        if (tableName.equals("teacher")){
            TeacherService teacherService = new TeacherServiceImpl();
            List<Teacher> teachers = teacherService.finAllTeachers();
//            for (Teacher teacher : teachers) {
//                System.out.println(teacher);
//            }
            jsonArray = JSONArray.fromObject(teachers);
        }
        if (tableName.equals("person")){
            PersonService personService = new PersonServiceImpl();
            List<Person> person = personService.finAllPerson();
//            for (Person person1 : person) {
//                System.out.println(person1);
//            }
            jsonArray = JSONArray.fromObject(person);
        }
//        System.out.println(jsonArray);
        request.setAttribute("jsonArray", jsonArray);
        request.setAttribute("tableName", tableName);
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doPost(request,response);
    }
}